// const { resolve } = require("path");

const db=wx.cloud.database();
const _ = db.command

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
//上传图片
var uploadFile= async (fileType,tempPath,targetPath,extraData)=>{
  return new Promise(
    (resolve, reject) => {
     var fileInfo={};
     wx.cloud.uploadFile({
       type: fileType,
       filePath: tempPath, 
       cloudPath: targetPath,
       formData: extraData,
       success: function (res) {
         fileInfo.fileId= res.fileID;
         console.log("上传成功!")
        //  console.dir(fileInfo);
         resolve(fileInfo.fileId)
       },
       fail: res => {
         wx.showToast({
           icon: 'error',
           title: '服务器错误,上传失败！',
           mask: true
         })
       }
     })
   }).then(res => {
     //res就是resolve传过来的that.data.a，都可以用
     console.log('传值res', res)
     return res;
   })
 }

//id查询数据库
const  queryDbById = async (collectionName,id) =>{
  return (await db.collection(collectionName).doc(id).get()).data
}
const getOpenID= async ()=>{
  return new Promise((resolve)=>wx.cloud.callFunction({name:'getopenid',success:(res)=>{resolve(res)}})).then(val=>{
    getApp().globalData.userInfo.openId=val.result.openid
    // console.log(val.result.openid)
    return val})
}
//openId查询数据库
const  queryDbByOpenId = async (collectionName,openid) =>{
  return new Promise((resolve)=>db.collection(collectionName).where({
    _openid:_.eq(openid)
  }).get({success:res=>{resolve(res.data)}})).then((val)=>{return val})//.data//{success:res=>{console.log(res.data[0])}}
}

//id删除数据库
const delDBbyId =async (collectionName,id)=>{
  db.collection(collectionName).doc(id).remove({
    success: function(res) {
      console.log(res.data)
    }
  })
}
const delFileByFileId=(filelist)=>{
  wx.cloud.deleteFile({
    fileList: filelist,
    success: res => {
      // handle success
      console.log(res.fileList)
    },
    fail: console.error
  })
}
const updateAvatar=(openid)=>{
  let app=getApp()
  db.collection('UserPublicInfo').where({_openid:_.eq(openid)}).get({success:res=>{app.globalData.userInfo.avatarUrl=res.data[0].avatarUrl;app.globalData.userInfo.nickName=res.data[0].nick_name}})
}

//查询集合中所有数据记录
const queryDbAll = async function (collectionName) {
  return (await db.collection(collectionName).get()).data
}
//分页查询
const queryDBbyLimt=async function(collectionName,skipNum,limitNum,condition){
  return (await db.collection(collectionName)
    .where(
      condition
    )
    // .field({
    //   name: true,
    //   price: true,
    // })
    .orderBy('like', 'desc')
    .skip(skipNum)
    .limit(limitNum)
    .get()
  ).data
}

//id更新数据库
const updateDbById = async (collectionName,id,keyvalue) =>{
  await db.collection(collectionName).doc(id).update({
    data:keyvalue
  })
}
//openid更新数据库
const updateDbByOpenId = async (collectionName,openid,keyvalue) =>{
  await db.collection(collectionName).where({_openid:_.eq(openid)}).update({
    data:keyvalue,
    success: function(res) {
      console.log('更新皮肤分析指标成功！')
      console.log(res.data.result)
    }
  })
}

//更新数据库
const updateDbAll = async (collectionName,keyValue) =>{
  await db.collection(collectionName).update({
    data:keyValue,
    success: function(res) {
      console.log(res.data)
    }
  })
}

//插入数据
const insertDbAll = async (collectionName,keyValue) =>{
  db.collection(collectionName).add({
    // data 字段表示需新增的 JSON 数据
    data:keyValue,
    success: function(res) {
      // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
      console.log(res)
    }
  })
}
//联表查询
const queryDbByLookup= async (collection1,collection2,key1,key2)=>{
     return new Promise ( 
       (resolve)=>  wx.cloud.callFunction({ //注意不要将Promise写成promise
      name:'querybylookup',
        // 传给云函数的参数
      data: {
        c1:collection1,
        c2:collection2,
        k1:key1,
        k2:key2
      },
      success:res=>{
        resolve(res);
      }
      ,
      fail: res => {
        console.error('callFunction fail: '+ res)
      }
    })).then((res)=>{
      return res;
    })
}
//获取用户信息
const getUInfo= async ()=>{
  let app=getApp();
  return new Promise( (resolve)=> wx.getUserProfile({
    desc:'用于完善用户信息',
    success:(res)=>{
      app.globalData.userInfo.nickName=res.userInfo.nickName
      app.globalData.userInfo.avatarUrl=res.userInfo.avatarUrl
      resolve(true)
    },
    fail:()=>{
      resolve(false)
    }
  })
  ).then(val=>{
    app.globalData.userInfo.hasUserInfo=val;
    console.log('获取用户头像昵称:'+val)
    return val;
  })
}
//新用户账户初始化
const initAccount = async () => {
  let app=getApp();
  if(!app.globalData.userInfo.hasUserInfo){
    let result=await getUInfo()
    if(result&&app.globalData.userInfo.openId){
      insertDbAll('UserPublicInfo',{
        avatarUrl:app.globalData.userInfo.avatarUrl,
        nick_name:app.globalData.userInfo.nickName,
        user_id:app.globalData.userInfo.openId,//唯一性限制
        fans:[],//粉丝
        subscribe:[],//关注
      }).then(
        ()=>insertDbAll('UserPrivateInfo',{
        remaining_times:0,
        skinAnalyzeInspect:'color,smooth,acnespotmole,wrinkle,eyesattr,blackheadpore,skinface,skinquality',
        total_cost:0,
        user_id:app.globalData.userInfo.openId,//唯一性限制
        shop_history:[],//购物
        stars:[],//收藏
        theme:0
      }
      ))
      app.globalData.userInfo.skinAnalyzeInspect='color,smooth,acnespotmole,wrinkle,eyesattr,blackheadpore,skinface,skinquality'//默认分析指标
      console.log('用户信息添加成功！')
      console.log(app.globalData.userInfo)
    }
  }
}

  /**
   * 获得百度Access_Token
   * new promise 实现同步返回新的token
   */
  const getAPIgrant = async function (key) {
    var client_id = key.API_Key; //client_id： 必须参数，应用的API Key；
    var client_secret = key.Secret_Key; //client_secret： 必须参数，应用的Secret Key；
    var Access_Token
    return new Promise(
      (resolve) => {
        wx.request({
          url: '自己修改' + client_id + '&client_secret=' + client_secret + '&',
          method: 'GET',
          dataType: 'json',
          success: res => {
            console.log('人脸检测API Access Token 请求成功!')
            const newTime = Math.round(Date.parse(res.header.Date)/1000) //Math.round(Date.parse(new Date())/1000);获取13位当前时间戳，/1000再向上取整，精确到秒
            //本次更新时间，保存到数据库
            updateDbById('自己修改', '自己修改', {
              ['lastUpdateTime']: newTime,
              ['Access_Token']: res.data.access_token,
              ['effictiveTime']: res.data.expires_in
            })
            Access_Token = res.data.access_token;
            console.log('新授权token:' + Access_Token);
            resolve(Access_Token)
          },
          fail: res => {
            console.log("人脸检测API Access Token请求失败:");
            console.log(res)
          }
        })
      }).then((value) => {
      // console.log(value)
      return value
    })
  }

  /**
   * 判断是否允许直接进行检测
   */
  const isDetectAllow = async ()=>{
    var num={}; var freeTimes=0; var paidTimes=0;
    let app=getApp();
    return new Promise((resolve)=>{
      num = db.collection("FaceInfo").count();//FaceInfo集合（权限为仅创建者可读写）中当前用户的测肤记录数,也是最后一条测肤记录的编号
      resolve(num)
    }).then((value)=>{
      app.globalData.userInfo.amount=value.total//total
      freeTimes = app.globalData.freeTimes//免费次数
      paidTimes = app.globalData.userInfo.remainingTimes//购买的次数
      console.log("皮肤分析历史记录数："+value.total)
      return ( value.total < (freeTimes+paidTimes) ) ? true : false;
    })
  }

module.exports = {
  formatTime,queryDbById,queryDbByOpenId,updateDbById,queryDbAll,getAPIgrant,isDetectAllow,updateDbAll,insertDbAll,getUInfo,queryDbByLookup,initAccount,getOpenID,getUInfo,updateAvatar,updateDbByOpenId,uploadFile,queryDBbyLimt,delDBbyId,delFileByFileId
}
